package com.hyyt.shopjsp.order.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hyyt.shopjsp.express100.Express100Thred;
import com.hyyt.shopjsp.express100.bean.TaskRequest;
import com.hyyt.shopjsp.express100.callback.demo.HttpRequest;
import com.hyyt.shopjsp.express100.callback.demo.JacksonHelper;
import com.hyyt.shopjsp.logistics.service.IShopCityCourierService;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hyyt.shopjsp.basic.pojo.BasicArea;
import com.hyyt.shopjsp.basic.pojo.BasicCustomer;
import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicAreaService;
import com.hyyt.shopjsp.basic.service.IBasicCustomerService;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.customer.pojo.ShopEvaluateGoods;
import com.hyyt.shopjsp.customer.service.IShopEvaluateGoodsService;
import com.hyyt.shopjsp.logistics.pojo.ShopCityCourier;
import com.hyyt.shopjsp.logistics.pojo.ShopLogistics;
import com.hyyt.shopjsp.logistics.service.IShopLogisticsService;
import com.hyyt.shopjsp.order.pojo.ShopOrders;
import com.hyyt.shopjsp.order.pojo.ShopOrdersOplog;
import com.hyyt.shopjsp.order.pojo.ShopOrdersList;
import com.hyyt.shopjsp.order.pojo.ShopShipping;
import com.hyyt.shopjsp.order.service.IShopOrdersOplogService;
import com.hyyt.shopjsp.order.service.IShopOrdersService;
import com.hyyt.shopjsp.order.service.IShopOrdersListService;
import com.hyyt.shopjsp.order.service.IShopShippingService;
import com.hyyt.shopjsp.returnsApply.pojo.ShopReturnsApply;
import com.hyyt.shopjsp.returnsApply.service.IShopReturnsApplyService;
import com.hyyt.shopjsp.store.info.pojo.ShopShopInfo;
import com.hyyt.shopjsp.store.info.service.IShopShopInfoService;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;

/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Wang Youchun on 2017/06/15 0024下午 3:56.
 */

@Controller
@RequestMapping("/back/orders")
public class ShopOrdersController extends BaseController{
	
	private Logger log = Logger.getLogger(ShopOrdersController.class);
	private String basePath = "/back/shop/order/";
	@Resource
	private IShopOrdersService shopOrdersService;//订单service接口
	@Resource
	private IBasicCustomerService basicCustomerService;//会员service接口
	@Resource
	private IShopShopInfoService shopShopInfoService;//店铺service接口
	@Resource
	private IShopShippingService shopShippingService;//发货详情service接口
	@Resource
	private IShopOrdersListService shopOrdersListService;//订单明细service接口
	@Resource
	private IShopEvaluateGoodsService shopEvaluateGoodsService;//评价service接口
	@Resource
	private IShopOrdersOplogService shopOrdersOPLogService;//订单日志service接口
	@Resource
	private IShopLogisticsService shopLogisticsService;//快递公司service接口
	@Resource
	private IBasicAreaService basicAreaService;//地区service接口
	@Resource
	private IShopReturnsApplyService shopReturnsApplyService;//退货service接口
	@Resource
	private IShopCityCourierService shopCityCourierService; //同城快递serivce接口
	/**
	 * 订单列表初始化
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoOrdersPage")
	public String gotoOrdersPage(){
		return basePath+"listOrders";
	}
	
	/**
	 * 未付款订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoUntreatedOrdersPage")
	public String gotoUntreatedOrdersPage(){
		return basePath+"untreatedOrderslist";
	}

	/**
	 * 已付款订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoUnpaidOrdersPage")
	public String gotoUnpaidOrdersPage(){
		return basePath+"unpaidOrderslist";
	}

	/**
	 * 已配货订单
	 * @param param 参数
	 * @return 返回到指定页面
	 */
	@RequestMapping("gotoWaitShipmentsOrdersPage")
	public String gotoWaitShipmentsOrdersPage(Map<String, Object> param){
		param.put("parentId",0);
        List<BasicArea> provinceList = basicAreaService.queryBasicArea(param);
        param.clear();
		param.put("provinceList", provinceList);
		return basePath+"waitShipmentsOrderslist";
	}

	/**
	 * 已发货订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoAlreadyShipmentsOrdersPage")
	public String gotoAlreadyShipmentsOrdersPage(){
		return basePath+"alreadyShipmentsOrderslist";
	}

	/**
	 * 已收货订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoValidationGoods")
	public String gotoValidationGoods(){
		return basePath+"validationGoodslist";
	}

	/**
	 * 待评价订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotopreEvaluate")
	public String gotopreEvaluate(){
		return basePath+"preEvaluateOrderslist";
	}

	/**
	 * 已评价订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoEvaluateList")
	public String gotoEvaluateList(){
		return basePath+"evaluateOrderslist";
	}

	/**
	 * 已取消订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoCancelOrdersPage")
	public String gotoCancelOrdersPage(){
		return basePath+"cancelOrderslist";
	}

	/**
	 * 已退货订单
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoReturnGoods")
	public String gotoReturnGoods(){
		return basePath+"returnApplylist";
	}
	/**
	 * 初始化订单列表
	 * @param page
	 * @param response
	 * @param request
	 */
	@RequestMapping(value="ordersList",method=RequestMethod.POST)
	@ResponseBody
	public void ordersList(Page page, HttpServletResponse response, HttpServletRequest request){
		String orderState=request.getParameter("orderState");
		String shopInfoType=request.getParameter("shopInfoType");
		String orderSource=request.getParameter("orderSource");
		String ordersNo=request.getParameter("ordersNo");
		String settlementStatus=request.getParameter("settlementStatus");
		Map<String, Object> params = new HashMap<>();
		if(Utils.objectIsNotEmpty(ordersNo)){
			params.put("ordersNo", ordersNo.trim());
		}
		if(Utils.objectIsNotEmpty(orderSource)){
			params.put("orderSource", orderSource);
		}
		if(Utils.objectIsNotEmpty(shopInfoType)){
			params.put("shopInfoType", shopInfoType);
		}
		if(Utils.objectIsNotEmpty(settlementStatus)){
			params.put("settlementStatus", settlementStatus);
		}
		if(Utils.objectIsNotEmpty(orderState)){
			params.put("ordersState", orderState);
		}
		params.put("sortColumns", "o.updateTime desc");
		int totalRecordCount =shopOrdersService.countShopOrders(params);
		 page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
		 List<ShopOrders> shopOrdersList  =shopOrdersService.queryShopOrders(params, page.getPageRecordBeginIndex(), page.getPageSize());
		 params.clear();
		 params.put("total", totalRecordCount);// total键 存放总记录数，必须的
		 params.put("rows", shopOrdersList);// rows键 存放每页记录 list
		 ResultMsg.create(params, response);  //把内容发送到页面
	}

	/**
     * 根据id获得对象
     *
     * @param ordersId
     */
    @RequestMapping(value = "getOrdersObject", method = RequestMethod.POST)
    @ResponseBody
	public ResultMsg getOrdersObject(Integer ordersId) {
		if (Utils.objectIsNotEmpty(ordersId)) {
			ShopOrders shopOrders = shopOrdersService.loadShopOrders(ordersId);//订单信息
			BasicCustomer basicCustomer = basicCustomerService.loadBasicCustomer(shopOrders.getCustomerId());//会员信息
			ShopShopInfo shopShopinfo = shopShopInfoService.loadShopShopInfo(shopOrders.getShopInfoId());//店铺信息
			Map<String, Object> params=new HashMap<>();
			Map<String, Object>queryMap=new HashMap<>();
			params.put("shopOrders", shopOrders);
			params.put("basicCustomer", basicCustomer);
			params.put("shopShopinfo", shopShopinfo);
			//得到发货详情对象
			ShopShipping shopShipping = shopShippingService.loadShopShipping(ordersId);
			params.put("shopShipping", shopShipping);
			//物流信息（json格式）
	        String content = "";
	        if (Utils.objectIsNotEmpty(shopShipping)) {
	            content = shopShipping.getExpressInfo();
	            if (Utils.objectIsNotEmpty(content)) {
	                // 将json字符串转换成jsonObject
	                JSONObject jsonObject = JSONObject.fromObject(content);
	                Iterator<?> it = jsonObject.keys();
	                // 遍历jsonObject数据，添加到Map对象
	                while (it.hasNext()) {
	                    String key = String.valueOf(it.next());
	                    Object value = jsonObject.get(key);
	                    params.put(key, value);
	                }
	            }
	        }
	        //查询订单明细
	        queryMap.put("ordersId", shopOrders.getOrdersId());
	        List<ShopOrdersList> shopOrderslist = shopOrdersListService.queryShopOrdersList(queryMap);
	        if (shopOrderslist != null && shopOrderslist.size() > 0) {
	        	ShopOrdersList ordersList2 = shopOrderslist.get(0);
	            BigDecimal discount = ordersList2.getDiscount();
	            params.put("zk", discount);//明细中的折扣
	        }
	      //查询评价信息
	        List<ShopEvaluateGoods> egList = shopEvaluateGoodsService.queryEvaluateGoodsList(queryMap);
	        params.put("egList", egList);
			return ResultMsg.create(true, null, FastJsonUtils.toJSONString(params));
		}
		return ResultMsg.create(false);
	}
	
	/**
	 * 异步查询订单商品
	 * @param response
	 * @param request
	 * @param ordersNo 订单号
	 */
    @RequestMapping(value="findOrdersProduct",method=RequestMethod.POST)
    @ResponseBody
	public ResultMsg findOrdersProduct(HttpServletResponse response, HttpServletRequest request,String ordersNo){
		if(Utils.objectIsNotEmpty(ordersNo)){
			Map<String, Object> params=new HashMap<>();
			params.put("orderNo", ordersNo);
			List<ShopOrdersList> productMap = shopOrdersListService.queryShopOrdersList(params);
			params.put("productMap", productMap);
			return ResultMsg.create(true, null, FastJsonUtils.toJSONString(params));
		}
		return ResultMsg.create(false);
	}

	/**
	 * 获得订单日志对象
	 * @param response
	 * @param request
	 * @param ordersNo 订单号
	 * @return
	 */
    @RequestMapping(value="getOrdersOPLogObject",method=RequestMethod.POST)
    @ResponseBody
	public ResultMsg getOrdersOPLogObject(HttpServletResponse response, HttpServletRequest request,String ordersNo){
		if(Utils.objectIsNotEmpty(ordersNo)){
			Map<String, Object> params=new HashMap<>();
			params.put("ordersNo", ordersNo);
			List<ShopOrdersOplog> ordersOPLogList = shopOrdersOPLogService.queryShopOrdersOPLog(params);
			params.put("ordersOPLogList", ordersOPLogList);
			return ResultMsg.create(true, null, FastJsonUtils.toJSONString(params));
		}
		return ResultMsg.create(false);
	}

	/**
     * 校验快递公司是否存在
     * @param servletResponse
     * @param code
     */
    @RequestMapping(value="checkShipments",method=RequestMethod.POST)
    @ResponseBody
	public ResultMsg checkShipments( HttpServletResponse servletResponse,String code){
		 boolean isHave = false;
		 Map<String, Object> params=new HashMap<>();
		 params.put("code", code);
		 int countShopLogistics = shopLogisticsService.countShopLogistics(params);
		 if (countShopLogistics > 0) {
			 isHave = true;
		 }
		 return ResultMsg.create(isHave);
	}

	/**
	 * 获取市
	 * @param response
	 * @param areaId
	 */
	@RequestMapping(value="findCityList",method=RequestMethod.POST)
	@ResponseBody
	public void findCityList(HttpServletResponse response,String areaId){
		Map<String, Object> params=new HashMap<>();
		params.put("parentId", areaId);
		List<BasicArea> cityList = basicAreaService.queryBasicArea(params);
		params.clear();
		params.put("cityList", cityList);
		ResultMsg.create(params,response);
	}

	/**
	 * 退货列表
	 * @param page
	 * @param response
	 */
	@RequestMapping("returnsApplyList")
	@ResponseBody
	public void returnsApplyList(Page page, String ordersNo,String orderSource,String shopInfoType,HttpServletResponse response){
		Map<String, Object> params = new HashMap<>();
		if(Utils.objectIsNotEmpty(ordersNo)){
			params.put("ordersNo", ordersNo.trim());
		}
		if(Utils.objectIsNotEmpty(orderSource)){
			params.put("orderSource", orderSource);
		}
		if(Utils.objectIsNotEmpty(shopInfoType)){
			params.put("shopInfoType", shopInfoType);
		}
		params.put("sortColumns", "createTime desc");
		int totalRecordCount =shopReturnsApplyService.countShopReturnsOrder(params);
		 page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
		 List<ShopReturnsApply> returnList  =shopReturnsApplyService.queryReturnsApplyList(params,page.getPageRecordBeginIndex(), page.getPageSize());
		 params.clear();
		 params.put("total", totalRecordCount);// total键 存放总记录数，必须的
		 params.put("rows", returnList);// rows键 存放每页记录 list
		 ResultMsg.create(params, response);  //把内容发送到页面
	}

	/**
	 * 更改订单正在配送状态
	 * @param ordersId
	 * @return
	 */
	@RequestMapping(value="saveOrUpdateOrdersStuts",method=RequestMethod.POST)
	@ResponseBody
	public ResultMsg saveOrUpdateOrdersStuts(String ordersId){
		boolean success = false;
		BasicUsers basicUsers = getSessionUsers();
		if (Utils.objectIsNotEmpty(basicUsers) && Utils.objectIsNotEmpty(ordersId)) {
			shopOrdersService.saveOrUpdateChanggeOrdersState(ordersId,basicUsers);
			success=true;
		}
		return ResultMsg.create(success);
	}

	/**
	 * 更改发货状态
	 * @param response
	 * @param request
	 * @param shipping
	 * @param cityCourier
	 * @param orders
	 * @param logisticsId
	 * @return
	 */
	@RequestMapping(value = "changeShipments",method = RequestMethod.POST)
    @ResponseBody
	public ResultMsg changeShipments(HttpServletResponse response,HttpServletRequest request, ShopShipping shipping,ShopCityCourier cityCourier,ShopOrders orders,String logisticsId){
		boolean isSuccess = false;
		String logisticsType=request.getParameter("logisticsType");
		String ordersId=request.getParameter("ordersId");
        BasicUsers users =  getSessionUsers();
		 if (logisticsType == "1" || "1".equals(logisticsType)){
			 if (users != null && orders != null && orders.getOrdersId() != null && shipping != null) {
				 ShopLogistics logistics = shopLogisticsService.loadShopLogisticsByCode(logisticsId);
				 shipping.setDeliveryUrl(logistics.getDeliveryUrl());
				 shipping.setDeliveryCorpName(logistics.getDeliveryCorpName());
				 shipping.setCode(logistics.getCode());
				 orders= shopOrdersService.saveOrUpdateChangeShipments(orders, shipping, users);
				 isSuccess = true;
				 try {
					 TaskRequest req = new TaskRequest();
					 //本网站所在路径
					 String callbackurl = String.valueOf(RedisDataReadUtil.getSysConfig("express100_callback_url"));
					 req.getParameters().put("callbackurl", callbackurl);//回调地址
					 //与快递公司签约key
					 String key = String.valueOf(RedisDataReadUtil.getSysConfig("express100_key"));
					 req.setKey(key);//与快递公司签约key
					 req.setTo(orders.getAddress());//收货人地址
					 req.setCompany(shipping.getCode());//快递公司
					 req.setNumber(shipping.getDeliverySn());//快递公司代号

					 HashMap<String, String> p = new HashMap<String, String>();
					 p.put("schema", "json");
					 p.put("param", JacksonHelper.toJSON(req));
					 //System.out.println("发送信息："+JacksonHelper.toJSON(req));
					 String ret;
					 //请求快递100时的编码
					 String express100Encoding = String.valueOf(RedisDataReadUtil.getSysConfig("express100_encoding"));
					 //订阅快递100时的路径
					 String express100Path = String.valueOf(RedisDataReadUtil.getSysConfig("express100_path"));
					 ret = HttpRequest.postData(express100Path, p, express100Encoding);
					 //重新订阅时的时间，单位秒
					 int time = Integer.parseInt(String.valueOf(RedisDataReadUtil.getSysConfig("express100_time")));
					 //请求失败默认重新请求次数
					 int number = Integer.parseInt(String.valueOf(RedisDataReadUtil.getSysConfig("express100_number")));
					 //请求订阅快递100
					 Express100Thred express100Thred = new Express100Thred(ret, time, number);
					 Thread express100ThredStart = new Thread(express100Thred);
					 express100ThredStart.start();
				 } catch (Exception e) {
					 logger.error(e);
				 }
			 }
		 }else if(logisticsType == "2" || "2".equals(logisticsType)){//同城快递
			 if (users != null && orders != null && orders.getOrdersId() != null && cityCourier != null){
				ShopCityCourier cityCourierTemp=shopCityCourierService.loadShopCityCourier(cityCourier.getCityCourierId());
				 orders=shopOrdersService.saveOrUpdateChangeShipments(orders, cityCourierTemp, users);
				 isSuccess = true;
			 }
		 }else {//线下自取
			 if (users != null && ordersId != null) {
				ShopOrders shopOrders=shopOrdersService.loadShopOrders(Integer.parseInt(ordersId));
				 shopOrders.setSendType(3);
				 shopOrders.setOrdersState(4);//改为已发货
				 shopOrders.setUpdateTime(new Timestamp(System.currentTimeMillis()));
				 shopOrdersService.updateShopOrders(shopOrders);
				 //插入订单日志
				 ShopOrdersOplog ordersOPLog=new ShopOrdersOplog();
				 ordersOPLog.setOrdersId(orders.getOrdersId());
				 ordersOPLog.setOrdersNo(shopOrders.getOrdersNo());
				 ordersOPLog.setOperatorTime(new Timestamp(System.currentTimeMillis()));
				 ordersOPLog.setOrdersOperateState(4);
				 ordersOPLog.setOoperatorId(users.getUsersId());//操作人id
				 ordersOPLog.setOoperatorSource("1");//1、后台用户；2、后台系统；3、前台顾客；
				 ordersOPLog.setOperatorName(users.getTrueName());//操作人name
				 shopOrdersOPLogService.saveShopOrdersOPLog(ordersOPLog);
				 isSuccess=true;
			 }
		 }
		return ResultMsg.create(isSuccess);
	}

	/**
	 * 确认收货
	 * @param ordersId 订单号
	 */
	@RequestMapping(value = "confirmReceipt",method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg confirmReceipt(String ordersId){
		//获得session中管理员信息
		BasicUsers users =  getSessionUsers();
		boolean isSuccess=false;
		//判断页面中传过来的订单Id不为空
		if(Utils.objectIsNotEmpty(ordersId)){
			//根据订单号查询出订单对象
			ShopOrders shopOrders = shopOrdersService.loadShopOrders(Integer.parseInt(ordersId));
			shopOrders.setOrdersState(5);//订单状态改为5：已收货
			shopOrders.setUpdateTime(new Timestamp(System.currentTimeMillis())); //订单修改时间，获取当前系统时间
			shopOrdersService.updateShopOrders(shopOrders); //修改订单对象订单状态
			//------以下为插入订单日志-------
			ShopOrdersOplog ordersOPLog=new ShopOrdersOplog(); //订单日志对象
			ordersOPLog.setOrdersId(Integer.parseInt(ordersId)); //订单Id
			ordersOPLog.setOperatorName(users.getUserName()); //操作人名，称取管理员名称
			ordersOPLog.setOperatorTime(new Timestamp(System.currentTimeMillis())); //操作时间，取当前系统时间
			ordersOPLog.setOoperatorId(users.getUsersId()); //操作人Id，取管理员Id
			ordersOPLog.setOrdersNo(shopOrders.getOrdersNo());//订单号
			ordersOPLog.setOrdersOperateState(5); //订单操作状态，5:确认收货
			ordersOPLog.setOoperatorSource("2"); //操作来源，(1、后台用户；2、后台系统；3、前台顾客；)
			ordersOPLog.setComments("确认收货"); //操作备注
			shopOrdersOPLogService.saveShopOrdersOPLog(ordersOPLog); //插入订单日志数据
			isSuccess=true;
		}
		return ResultMsg.create(isSuccess);
	}
}
